#include "stm32f10x.h"                  // Device header
#include <time.h>

struct 
{
    uint16_t year;              
    uint8_t hour;               // 0-23       
    uint8_t minute;             // 0-60 
    uint8_t second;             // 0-60  (0 - 60 allows for the occasional leap second) */
    uint8_t month;              // 1-12
    uint8_t day;                // 1-31
    uint8_t weekday;            // 1-7
}Time;

/*RTC_EnterConfigMode 和 RTC_ExitConfigMode 都是不用写的，在库函数内部调用过了*/
// 可以借助备份寄存器来实现 断主电源依然保存时间
void MyRTC_Init(void)
{
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_PWR, ENABLE);     // Enable PWR
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_BKP, ENABLE);     // Enable BKP

    PWR_BackupAccessCmd(ENABLE);                            // Enable

    RCC_LSEConfig(RCC_LSE_ON);                              // Enable LSE
    while (RCC_GetFlagStatus(RCC_FLAG_LSERDY) == RESET);    // Wait until LSE is ready

    // RCC_RTCCLKConfig(RCC_RTCCLKSource_LSI);              //使用内部低速时钟
    RCC_RTCCLKConfig(RCC_RTCCLKSource_LSE);                 // Select LSE as RTC clock source 选择外部低速时钟
    RCC_RTCCLKCmd(ENABLE);                                  // Enable RTC clock

    RTC_WaitForSynchro();                                   // Wait until RTC registers are synchronized
    RTC_WaitForLastTask();                                  // 等待任务完成

    RTC_SetPrescaler(32768 - 1);                            // 设置RTC预分频器的值使得周期为1s
    RTC_WaitForLastTask();                                  // 等待任务完成

    RTC_SetCounter(1708361523);                             // 设置RTC计数器的值 翻译为2024-02-20 00:52:03
    RTC_WaitForLastTask();                                  // 等待任务完成
}

void MyRTC_WriteTime(void)
{
    time_t time_cnt;
    struct tm time_date = 
    {
        .tm_year = Time.year - 1900,
        .tm_mon = Time.month - 1,
        .tm_mday = Time.day,
        .tm_hour = Time.hour,
        .tm_min = Time.minute,
        .tm_sec = Time.second
    };

    time_cnt = mktime(&time_date) - 8 * 60 * 60;                  // 转换成东8区时间
    RTC_SetCounter(time_cnt);
}

void MyRTC_ReadTime(void)
{
    time_t time_cnt;
    struct tm time_date;
    time_cnt = RTC_GetCounter() + 8 * 60 * 60;                    // 转换成东8区时间
    time_date = *localtime(&time_cnt);                            // 获取当前时间，默认是伦敦时间
    Time.year = time_date.tm_year + 1900;
    Time.month = time_date.tm_mon + 1;
    Time.day = time_date.tm_mday;
    Time.hour = time_date.tm_hour;
    Time.minute = time_date.tm_min;
    Time.second = time_date.tm_sec;
    Time.weekday = time_date.tm_wday;
}   
